//
//  NSObject+Reflent.swift
//  MySport
//
//  Created by lanou3g on 16/2/27.
//  Copyright © 2016年 ccsobj. All rights reserved.
//

import UIKit
// 获取项目的命名空间
public let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String


extension NSObject{
    var mirror:Mirror{
        return Mirror(reflecting:self)
    }
    
    func className()->String?{
        let claz = mirror.subjectType as! AnyClass
        let name:String = NSStringFromClass(claz)
        return name.removeNamespace()
    }
    func propertyList()->[NSObject:AnyObject]?{
        var dict:[NSObject:AnyObject]! = [NSObject:AnyObject]()
        for (lable,value) in mirror.children{
            if let obj = value as? NSObject{
                if !obj.isFundationObject() {
                   obj.propertyList()
                    dict[lable!] = obj
                    continue
                }
            }
            dict[lable!] = (value as! AnyObject)
        }
        return dict
    }
    
    
    
    private func displayStyle(instance:Any) -> Mirror.DisplayStyle?{
        return Mirror(reflecting:instance).displayStyle
    }
    
    private class func isClass()->Bool{
        if let obj = self as? NSObject{
            return !obj.isFundationObject()
        }else{
            return false
        }
    }
    
    private func  isFundationObject()->Bool{
        if self.fitClassArray([NSString.self,NSValue.self]){
            return true
        }
        return false
    }
    
    private func fitClassArray(clazzs:[AnyClass])->Bool{
        for clazz in clazzs{
            if self .isKindOfClass(clazz){
                return true
            }
        }
        return false
    }
}


extension String{
    func removeNamespace()->String{
        return self.stringByReplacingOccurrencesOfString(namespace + ".", withString:"")
    }
    
    func addNamespace()->String{
        return namespace + "." + self
    }
    
    func object()->AnyObject?{
        let clazz = NSClassFromString(self.addNamespace())
        if let c = (clazz as? NSObject.Type){
            return c.init()
        }
        return nil
    }
}
